const path = require('path');
const PackEngine = require('./packEngine');
const applyDefaultPlugins = require('./applyDefaultPlugins');
const CachedInputFileSystem = require('./CachedInputFileSystem');
const fs = require('graceful-fs');

const getConfig = () => {
    const configPath = path.resolve(__dirname, '../webpack.config.js');
    const config = require(configPath);

    return { ...config, path: configPath, context: process.cwd() };
}

const createPackEngine = () => {
    const config = getConfig();
    console.log('---------- get webpack config ----------');
    const packEngine = new PackEngine(config.context);
    console.log('---------- packEngine created -----------');
    packEngine.options = config;

    // 输入输出系统
    compiler.inputFileSystem = new CachedInputFileSystem(fs, 60000);
    compiler.outputFileSystem = fs;

    // 执行webpack.config中的plugins
    if (Array.isArray(config.plugins)) {
        for (const plugin of config.plugins) {
            if (typeof plugin === 'function') {
                plugin.call(packEngine, packEngine);
            } else {
                plugin.apply(packEngine);
            }
        }
    }

    // 应用预置的plugin
    applyDefaultPlugins(options, packEngine);

    return packEngine;
}

const run = () => {
    console.log('---------- pack start ----------');

    const packEngine = createPackEngine();

    packEngine.run();
}

module.exports = {
    run,
}
